<?php


namespace App\Controller;

use App\Model\User;
use Asf\Http\JsonResponse;
use Asf\Http\RedirectResponse;
use Asf\Http\Request;
use Asf\Http\Response;
use Asf\Support\Env;
use Asf\Util\Context;

class IndexController
{
    public function index(Request $request)
    {
        $users = User::all();
        return view('index.html', compact('users'));
    }

    //创建页面
    public function create(Request $request)
    {
        return view('create.html');
    }

    //创建操作
    public function store(Request $request)
    {
        $user = new User();
        $user->name = $request->get('name');
        $user->password = $request->get('password');
        $user->age = $request->get('age');

        $user->save();

        return new RedirectResponse('/user');
    }

    //编辑页面
    public function edit(Request $request, $id)
    {
        $user = User::find($id);

        return view('edit.html', ['user' => $user]);
    }

    //编辑操作
    public function update(Request $request, $id)
    {
        $user = User::find($id);
        $user->name = $request->get('name');
        $user->password = $request->get('password');
        $user->age = $request->get('age');

        $user->save();
        return new RedirectResponse('/user');
    }

    //删除操作
    public function delete($id)
    {
        User::destroy($id);

        return new JsonResponse([
            'state' => 'ok',
            'message' => '删除成功',
        ]);
    }
}